package servlet.play;

import com.alibaba.fastjson.JSON;
import pojo.Result;
import pojo.Songs;
import service.SongsService;
import service.impl.SongsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@WebServlet("/play/playMusic")
public class PlayMusic extends HttpServlet {
    private SongsService musicService = new SongsServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 设置请求的字符编码为 UTF-8，确保能正确解析包含中文等特殊字符的参数
            request.setCharacterEncoding("utf-8");

            // 从请求中获取名为 "songIds" 的参数
            String songIdsParam = request.getParameter("songIds");
            if (songIdsParam == null || songIdsParam.isEmpty()) {
                return;
            }

            int songIds = Integer.parseInt(songIdsParam);
            Songs song = musicService.selectSongById(songIds);
            // 根据 songIds 获取音乐 URL
            String url = song.getFilePath();
            String title = song.getTitle();
            // 将 url 存储到请求属性中，以便在后续的 JSP 页面中使用
            request.getSession().setAttribute("songUrl", url);
            request.getSession().setAttribute("title", title);
            // 获取文件的真实路径，根据title，查找歌词文件夹lrc/中包含title的文件路径
            String fileName = getServletContext().getRealPath("lrc/" + title + ".lrc");
            // 如果fileName为空，这设置歌词提示：“本地暂无此歌词”
            if (fileName == null || fileName.isEmpty()) {
                request.getSession().setAttribute("lyrics", "本地暂无此歌词");
            }else {
                String lyrics = readFileByLines(fileName);    // 歌词文件
                request.getSession().setAttribute("lyrics", lyrics);
            }

            // 返回重定向 URL，前端可以捕获该信息并跳转
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"redirectUrl\": \"" + request.getContextPath() + "/play/play.jsp\"}");
        } catch (Exception e) {
            // 打印异常信息，便于调试和问题定位
            e.printStackTrace();
            // 返回错误响应
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"code\": 0, \"message\": \"play error\"}");
        }
    }

    public static String readFileByLines(String fileName) {
        File file = new File(fileName);
        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(new FileInputStream(file), "utf-8");
            BufferedReader bufferedReader = new BufferedReader(reader);
            String tempString = null;
            String songs = "";
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = bufferedReader.readLine()) != null) {
                // 显示行号
                songs = songs + tempString + "\r\n";
            }
//            System.out.println(songs);
            bufferedReader.close();
            return songs;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }
}
